package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     */
    @CacheEvict(value = "dish",key = "#dishDto.categoryId+':'+#dishDto.status")
    @PostMapping
    public R saveDish(@RequestBody DishDto dishDto) {
        log.info("新增菜品");
        log.info(dishDto.toString());
        //对菜品进行修改之后
        //需要清空缓存
//        //第一种方式,清理所有菜品缓存数据
//        Set keys = redisTemplate.keys("dish:*"); //获取所有dish:开头的key
//        redisTemplate.delete(keys);//删除这些key
        dishService.addWitnFlavor(dishDto);

        //第二种方式,只清理该菜品所在分类的缓存数据
//        Set keys = redisTemplate.keys("dish:" + dishDto.getCategoryId() + "_1");
//        redisTemplate.delete(keys);

        return R.success("添加成功");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageQurry(Integer page, Integer pageSize, String name) {
        log.info("菜品分页查询");

        //分页构造器
        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        //查询构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByAsc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);

        //总条目数
        int total = (int) pageInfo.getTotal();
        Map map = new HashMap<>();
        map.put("total", total);

        //查询列表数据
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            //拷贝dish的属性数据到dishDto中
            BeanUtil.copyProperties(dish, dishDto);
            //获取categoryName
            //获取菜品id
            Long id = dish.getCategoryId();
            //通过菜品id获取分类信息
            Category category = categoryService.getById(id);
            //获取分类信息内的分类名称
            String categoryName = category.getName();
            //给dishDto设置分类名称属性
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        map.put("records", dishDtos);

        return R.success(map);
    }

    /**
     * 根据id查询菜品数据,用于回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id查询菜品数据,用于回显");

        DishDto dishDto = new DishDto();
        //查询菜品数据,copy给dishDto
        Dish dish = dishService.getById(id);
        BeanUtil.copyProperties(dish, dishDto);

        //查询菜品的口味数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(lqw);

        //设置dishDto的口味数据
        dishDto.setFlavors(list);

        return R.success(dishDto);
    }

    /**
     * 修改菜品数据
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dish",allEntries = true)
    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto) {
        log.info("修改菜品数据");
        //存储数据到dish表
        dishService.updateById(dishDto);
        //第二种方式,只清理该菜品所在分类的缓存数据
//        Set keys = redisTemplate.keys("dish:" + dishDto.getCategoryId() + "_1");
//        redisTemplate.delete(keys);
        //获取菜品id
        Long id = dishDto.getId();
        //根据菜品id删除flavor表中的数据
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        dishFlavorService.remove(lqw);
        //存储数据到dishFlavor表
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //设置flavor表中的菜品id
            flavor.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
        return R.success("修改成功");
    }

    /**
     * 根据id删除/批量删除数据(逻辑删除)
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dish",allEntries = true)
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids) {
        log.info("根据id删除");
        //判断该菜品是否存在某个套餐里面
        //如果存在,则给出提示,不能删除
        for (Long id : ids) {
            //先获取菜品的分类id
            Long categoryId = dishService.getById(id).getCategoryId();
            //判断这个分类是否是套餐
            if (categoryService.getById(categoryId).getType() != 1) {
                return R.error("有菜品关联套餐,无法删除...");
            }
        }
        //先删除菜品对应的口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(lqw);
        //再删除菜品
        dishService.removeByIds(ids);

        //第二种方式,只清理该菜品所在分类的缓存数据
//        List<Long> categoryIds = null;
//        for (Long id : ids) {
//            //先获取菜品的分类id
//            categoryId = dishService.getById(id).getCategoryId();
//        }
//
//        Set keys = redisTemplate.keys("dish:*");
//        redisTemplate.delete(keys);

        return R.success("删除成功");
    }

    /**
     * 设置菜品状态 : 启售/停售 / 批量启售/批量停售
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "dish",allEntries = true)
    @PostMapping("/status/{status}")
    public R updateDishStatus(@PathVariable Integer status,
                              @RequestParam List<Long> ids) {
        log.info("设置菜品状态");
        log.info(status.toString());
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            /*Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);*/
            dishService.updateById(dish);
        }

        //update dish set status = ? where id in (1,2,3)
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Dish::getStatus, status);
        lqw.in(Dish::getId, ids);

        dishService.update(lqw);
//        Set keys = redisTemplate.keys("dish:*");
//        redisTemplate.delete(keys);

        return R.success("操作成功");
    }

    /**
     * 根据分类id查询所有菜品集合(增加菜品口味数据)
     *
     * @param categoryId
     * @return
     */
    @Cacheable(value = "dish",key = "#categoryId+':'+#status")
    @GetMapping("/list")
    public R<List<DishDto>> getDish(Long categoryId, Integer status) {
        log.info("根据分类id查询所有菜品集合");

        List<DishDto> dishDtos = null;
        //设置key
//        String key = "dish:" + categoryId + "_" + status;
        //Redis优化  通用逻辑:先从缓存取,取到了直接返回 ; 取不到,查询数据库,获取结果,放入缓存,并返回
        //先从redis中返回缓存数据
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//        dishDtos = (List<DishDto>) valueOperations.get(key);

        if (dishDtos != null) { //存在
            return R.success(dishDtos);
        }
        //不存在
        //根据分类id查询所有菜品集合
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, categoryId).eq(Dish::getStatus, status);
        List<Dish> dishList = dishService.list(lqw);

        dishDtos = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //将dish属性属性据拷贝给dishDto
            BeanUtil.copyProperties(dish, dishDto);
            //查询dish相关的口味信息
            LambdaUpdateWrapper<DishFlavor> lqw2 = new LambdaUpdateWrapper<>();
            lqw2.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw2);
            //将dish相关的口味信息设置给dishDto
            dishDto.setFlavors(dishFlavors);
            dishDtos.add(dishDto);
        }
        //将分类菜品数据放入Redis
//        valueOperations.set(key, dishDtos, 60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
